<!-- eslint-disable vue/valid-v-for -->
<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="8" :xs="24">
      <ContentWrap class="h-1/1">
        <div class="head-container">
          <el-button type="primary" @click="addTopCategory">添加顶级分类</el-button>
          <el-button type="primary" @click="addCategory">添加子分类</el-button>
          <el-tree
            ref="treeRef"
            :data="categoryTree"
            :expand-on-click-node="false"
            :props="defaultProps"
            highlight-current
            node-key="id"
            @node-click="handleNodeClick"
            :default-checked-keys="defaultExpKeys"
          />
        </div>
      </ContentWrap>
    </el-col>
    <el-col :span="16" :xs="24">
      <ContentWrap class="h-1/1">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="80px"
        >
          <el-form-item label="上级分类" prop="parentId" v-if="formData.parentId > 0">
            <el-tree-select
              v-model="formData.parentId"
              :data="categoryTree"
              :props="defaultProps"
              check-strictly
              default-expand-all
              placeholder="请选择上级分类"
              value-key="categoryId"
            />
          </el-form-item>
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="分类编号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入分类编号" />
          </el-form-item>
          <el-form-item label="显示排序" prop="sort">
            <el-input-number v-model="formData.sort" :min="0" controls-position="right" />
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button type="primary" @click="deleCategory(formData.id)">删除</el-button>
      </ContentWrap>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { defaultProps, handleTree } from '@/utils/tree'
import * as CategoryApi from '@/api/infra/category'
import { CommonStatusEnum } from '@/utils/constants'

defineOptions({ name: 'InfraCategory' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const radio = ref('1')
const radio1 = ref('1')
const categoryTree = ref<Tree[]>([]) // 树形结构
const getTree = async () => {
  const res = await CategoryApi.getSimpleCategoryList()
  // let dept: Tree = { id: 0, name: '顶级部门', children: [] }
  // dept.children = handleTree(res)
  console.log(res);

  categoryTree.value = []
  categoryTree.value.push(...handleTree(res))
  console.log(...handleTree(res));

  formData.value = await CategoryApi.getCategory(categoryTree.value[0].id)
  formType.value = 'update'
}
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  title: '',
  parentId: undefined,
  name: undefined,
  sort: undefined,
  code: undefined,
  status: CommonStatusEnum.ENABLE
})
const formRules = reactive({
  parentId: [{ required: true, message: '上级分类不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '分类编号不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const defaultExpKeys = ref([])
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  // 删除的二次确认
  await message.confirm('确认' + formType.value + '该分类')
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CategoryApi.CategoryVO
    if (formType.value === 'update') {
      await CategoryApi.updateCategory(data)
      message.success(t('common.updateSuccess'))
    } else {
      await CategoryApi.createCategory(data)
      message.success(t('common.createSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
    await getTree()
  } finally {
    formLoading.value = false
  }
}

const addTopCategory = () => {
  formData.value = {
    id: undefined,
    title: '',
    parentId: 0,
    name: undefined,
    sort: undefined,
    leaderUserId: undefined,
    phone: undefined,
    email: undefined,
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
  formType.value = 'create'
}
const addCategory = () => {
  formData.value = {
    id: undefined,
    title: '',
    parentId: selectNode.value,
    name: undefined,
    sort: 0,
    leaderUserId: undefined,
    phone: undefined,
    email: undefined,
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
  formType.value = 'create'
}
const selectNode = ref()
const handleNodeClick = async (row: { [key: string]: any }) => {
  defaultExpKeys.value.push(row.id)
  selectNode.value = row.id
  formType.value = 'update'
  formData.value = await CategoryApi.getCategory(row.id)
}
/** 删除按钮操作 */
const deleCategory = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    const res = await CategoryApi.deleteCategory(id)
    if (res.data) {
      message.success(t('common.delSuccess'));
    } else {
      message.error("有子分类无法删除")
    }
    // 刷新列表
    await getTree()
  } catch {}
}
/** 初始化 **/
onMounted(async () => {
  await getTree()
})
</script>
